package com.suriya.thirukural;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.Set;
import java.util.TreeSet;

import com.suriya.thirukural.ThirukuralContext.WidgetInfo;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class KuralWidgetConfigure extends Activity
{
    private ThirukuralContext _context;
    private ListView          _menu;
    AssetManager              assetManager;
    int                       depth        = 0;
    int[]                     section      = null;
    private int               mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    private AppWidgetManager  appWidgetManager;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        _context = (ThirukuralContext) getApplication();
        _context.init();

        getWindow().setFormat(PixelFormat.RGBA_8888);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);

        assetManager = getAssets();
        appWidgetManager = AppWidgetManager.getInstance(this);
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if(extras != null)
        {
            mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }
        setResult(RESULT_CANCELED, null);

        // section = intent.getIntArrayExtra("section");
        if(section == null) section = new int[0];
        // depth = intent.getIntExtra("depth", 0);

        Log.d("Suriya", "Depth:" + depth);

        setContentView(R.layout.configure_main);
        LinearLayout layout = (LinearLayout) findViewById(R.id.screenview);
        layout.setBackgroundDrawable(_context.getBackgroundImage());

        _menu = (ListView) findViewById(android.R.id.list);
        Button but = (Button) findViewById(R.id.save);
        CheckBox chkbox = (CheckBox) findViewById(R.id.with_bg);
        chkbox.setChecked(bg);
        
        chkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                bg = isChecked;
            }
       });

        but.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v)
            {
                if(selectionIds.size() == 0)
                {

                }
                else
                {
                    _saveWidget();
                    finish();
                }
            }
        });

        String sectionStr = "sections";
        String expName = "section_";

        for(int currSection : section)
        {
            sectionStr += ("/" + currSection);
            expName += ("" + currSection + "_");
        }

        {
            String imgPath = "sections/";
            String filenamePart = "section";

            for(int idx = 1; idx <= depth && idx <= 3; idx++)
            {
                filenamePart += "_" + section[idx - 1];
                ImageView img = null;
                if(idx == 1)
                {
                    img = (ImageView) findViewById(R.id.imgsec1);
                }
                else if(idx == 2)
                {
                    img = (ImageView) findViewById(R.id.imgsec2);
                }
                else if(idx == 3)
                {
                    img = (ImageView) findViewById(R.id.imgsec3);
                }

                Log.d("Suriya", "Loading image:" + imgPath + filenamePart + ".png");
                if(img != null) img.setImageBitmap(getBitmap(assetManager, this, imgPath + filenamePart + ".png"));

                imgPath += "" + section[idx - 1] + "/";

            }
        }

        if(depth < 3)
        {
            LinkedList<String> list = new LinkedList<String>();

            try
            {
                Log.d("Suriya", "SectionStr:" + sectionStr);
                Set<String> availableSections = new TreeSet<String>();

                for(String curr : assetManager.list(sectionStr))
                {
                    if(curr.startsWith("section_"))
                    {
                        availableSections.add(curr);
                    }
                }

                int idx = 0;
                while(true)
                {
                    idx++;

                    String filename = expName + idx + ".png";
                    if(availableSections.contains(filename))
                    {
                        list.add(sectionStr + "/" + filename);
                        continue;
                    }
                    break;
                }

            }
            catch(IOException e)
            {
            }

            String[] items = list.toArray(new String[] {});
            _menu.setAdapter(new SectionArrayAdapter(_context, items));
        }
    }

    public void onGotoMainMenu(View v)
    {
        return;
    }

    public static Bitmap getBitmap(AssetManager assetManager, Context context, String filename)
    {
        try
        {
            InputStream stream = assetManager.open(filename);
            BufferedInputStream bis = new BufferedInputStream(stream);
            Bitmap ret = BitmapFactory.decodeStream(bis);

            int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 25.0,
                                                         context.getResources().getDisplayMetrics());
            int width = ret.getWidth() * height / ret.getHeight();
            ret = Bitmap.createScaledBitmap(ret, width, height, true);
            bis.close();
            stream.close();
            return ret;
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    class SectionArrayAdapter extends ArrayAdapter<String>
    {
        private LayoutInflater mInflater;

        public SectionArrayAdapter(Context context, String[] items)
        {
            super(context, R.layout.section_selection, items);
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view;
            if(convertView == null)
            {
                view = mInflater.inflate(R.layout.section_selection, parent, false);
            }
            else
            {
                view = convertView;
            }

            ImageView img = (ImageView) view.findViewById(R.id.image);
            CheckBox box = (CheckBox) view.findViewById(R.id.adikaram);

            box.setOnCheckedChangeListener(new MySelectionChanged(position));
            String item = getItem(position);

            view.setTag(item);
            try
            {
                InputStream stream = assetManager.open(item);
                BufferedInputStream bis = new BufferedInputStream(stream);
                Bitmap bm = BitmapFactory.decodeStream(bis);
                bis.close();
                stream.close();
                img.setImageBitmap(bm);
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }

            return view;
        }
    }

    Set<Integer> selectionIds = new TreeSet<Integer>();
    boolean      bg           = false;

    private void _saveWidget()
    {
        WidgetInfo info = new WidgetInfo();
        info.kuralTopics.addAll(selectionIds);
        info.background = bg;

        _context.saveWidget(mAppWidgetId, info);
        RemoteViews views = KuralWidgetService.buildRemoteView(_context, info, mAppWidgetId);
        appWidgetManager.updateAppWidget(mAppWidgetId, views);
        Intent resultValue = new Intent();
        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        setResult(RESULT_OK, resultValue);
    }

    class MySelectionChanged implements OnCheckedChangeListener
    {
        final int _pos;

        public MySelectionChanged(int position)
        {
            _pos = position;
        }

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if(isChecked)
                selectionIds.add(_pos);
            else
                selectionIds.remove(_pos);
        }
    }
}